package exercise04;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class MyRedPack2 implements Runnable{
    int count = 3;
    BigDecimal money = BigDecimal.valueOf(100.0);
    final BigDecimal MIN = BigDecimal.valueOf(0.01);
    private double randomDouble(double minVal,double maxVal){
        return minVal+Math.random()*(maxVal-minVal);
    }
    @Override
    public void run() {
        synchronized (MyRedPack2.class){
            if (count == 0){
                System.out.println(Thread.currentThread().getName()+",没有抢到红包");
            }else{
                BigDecimal prize;
                if (count == 1){
                    prize = money;
                }else{
                    // double brouns = money - (count-1)*MIN;
                    double brouns = money.subtract(BigDecimal.valueOf(count-1).multiply(MIN)).doubleValue();
                    prize = BigDecimal.valueOf(randomDouble(0.01,brouns));
                }
                //设置抽中红包，小数点保留两位，四舍五入
                prize = prize.setScale(2, RoundingMode.HALF_UP);
                //在总金额中去掉对应的钱
                money = money.subtract(prize);
                //红包少了一个
                count--;
                System.out.println(Thread.currentThread().getName()+",抢到"+prize+"元");
            }
        }
    }
}
